<?php
use think\Db;
use think\Queue;
use think\Config;

/**
 * 获取分类所有子分类
 * @param int $cid 分类ID
 * @return array|bool
 */
function get_category_children($cid)
{
    if (empty($cid)) {
        return false;
    }

    $children = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->select();

    return array2tree($children);
}

/**
 * 根据分类ID获取文章列表（包括子分类）
 * @param int   $cid   分类ID
 * @param int   $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['path' => ['like', "%,{$cid},%"]])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'cid', 'title', 'introduction', 'thumb', 'reading', 'publish_time'], (array)$filed);
    $map    = array_merge(['cid' => ['IN', $ids], 'status' => 1, 'publish_time' => ['<= time', date('Y-m-d H:i:s')]], (array)$where);
    $sort   = array_merge(['is_top' => 'DESC', 'sort' => 'DESC', 'publish_time' => 'DESC'], (array)$order);

    $article_list = Db::name('article')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}
/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}
/**
 * 构建层级（树状）数组(排序2级才生效)
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{

    $counter = array_children_count($array, $pid_name);

    if (!isset($counter[0]) || $counter[0] == 0) {

        return $array;
    }

    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);

        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {

            array_push($array, $temp);

        } else {
            if ($temp[$pid_name] == 0) {

                $tree[] = $temp;

            } else {
                if(count($array)>0){
                    $sort = array_column($array,'sort');
                    array_multisort($sort, SORT_DESC, $array);//排序处理
                }
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }

        $counter = array_children_count($array, $pid_name);
    }
    if(count($tree)>0){
        $sort = array_column($tree,'sort');
        array_multisort($sort, SORT_DESC, $tree);//排序处理
    }
    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if (is_dir($dir_name)) {
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}
/**
 * 获取目录中所有文件的路径
 * @param $dir
 * @return array
 */
function get_dir_file($dir)
{
    if(is_dir($dir)){
        $files = array();
        $child_dirs = scandir($dir);
        foreach($child_dirs as $child_dir){
            //'.'和'..'是Linux系统中的当前目录和上一级目录，必须排除掉，
            //否则会进入死循环，报segmentation falt 错误
            if($child_dir != '.' && $child_dir != '..'){
                if(is_dir($dir.'/'.$child_dir)){
                    $files[$child_dir] = get_dir_file($dir.'/'.$child_dir);
                }else{
                    $files[] = $child_dir;
                }
            }
        }
        return $files;
    }else{
        return false;
    }
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile()
{
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^(13|14|15|16|17|18|19)[0-9]{1}\d{8}$#';

    return preg_match($reg, $mobile) ? true : false;
}

//获取当月最后一天
function getLastDay(){
    $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
    return  date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));

}
/**
 * 把数字1-1亿换成汉字表述，如：123->一百二十三
 * @param [num] $num [数字]
 * @return [string] [string]
 */
function numToWord($num)

{
    $chiNum = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    $chiUni = array('','拾', '佰', '仟', '万', '亿', '拾', '佰', '仟');
    $chiStr = '';
    $num_str = (string)$num;
    $count = strlen($num_str);
    $last_flag = true; //上一个 是否为0
    $zero_flag = true; //是否第一个
    $temp_num = null; //临时数字
    $chiStr = '';//拼接结果
    if ($count == 2) {//两位数
        $temp_num = $num_str[0];
        $chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
        $temp_num = $num_str[1];
        $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
    }else if($count > 2){
        $index = 0;
        for ($i=$count-1; $i >= 0 ; $i--) {
            $temp_num = $num_str[$i];
            if ($temp_num == 0) {
                if (!$zero_flag && !$last_flag ) {
                    $chiStr = $chiNum[$temp_num]. $chiStr;
                    $last_flag = true;
                }
            }else{
                $chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
                $zero_flag = false;
                $last_flag = false;
            }
            $index ++;
        }
    }else{
        $chiStr = $chiNum[$num_str[0]];
    }
    return $chiStr;

}

//获取域名
function get_current_domain(){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])){
        return $sys_protocal.$_SERVER['HTTP_X_FORWARDED_HOST'];
    }
    else if (isset($_SERVER['HTTP_HOST'])) {
        //dump($_SERVER['HTTP_HOST']);exit;
        return $sys_protocal.$_SERVER['HTTP_HOST'];
    }

    return "";
}


function redis($db=0) {
    $con = new \Redis();
    $con->connect(config('redis.host'), config('redis.port'), config('redis.timeout'));
    if(config('redis.password')){
        $con->auth(config('redis.password'));
    }
    $con->select($db);
    return $con;
}

function getOssUrl($url){
    return $url;
    $local = env("local");
    if($local=="localhost"){
        return $url;
    }
    $aloss = new app\Service\AliyunOss();

    $asurl = $aloss->getSginurl($url);
    $asurl = str_replace("+","%2b",$asurl);
    return $asurl;
}

//时间格式化（时间戳）
function uc_time_ago($ptime) {
    date_default_timezone_set('PRC');
    //$ptime = strtotime($ptime);
    $etime = time() - $ptime;
    if($etime == 0){
        $msg = '刚刚';
    }elseif($etime <= 60){
        $msg = $etime.'秒前';
    }elseif($etime > 60 && $etime <= 60 * 60){
        $msg = floor($etime / 60) . '分钟前';
    }elseif($etime > 60 * 60 && $etime <= 24 * 60 * 60){
        $msg = date('Ymd',$ptime)==date('Ymd',time()) ? '今天 '.date('H:i',$ptime) : '昨天 '.date('H:i',$ptime);
    }elseif($etime > 24 * 60 * 60 && $etime <= 2 * 24 * 60 * 60){
        $msg = date('Ymd',$ptime)+1==date('Ymd',time()) ? '昨天 '.date('H:i',$ptime) : '前天 '.date('H:i',$ptime);
    }else{
        $msg = date('Y/m/d H:i',$ptime);
    }
    return $msg;
}
//名字隐藏部分
function substr_cut($user_name){
    $strlen     = mb_strlen($user_name, 'utf-8');
    $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}


function exist_check($value,$rule){
    $ruleItems = explode(",",$rule);
    if (empty($ruleItems)){
        throw new \think\exception\ValidateException("table undefined");
    }
    if (count($ruleItems) == 1){
        $pk = \think\facade\Db::getPk($ruleItems[0]);
        array_push($ruleItems,$pk);
    }
    list($table,$field) = $ruleItems;
    $result = \think\facade\Db::table($table)->where($field, $value)->find();
    if ($result){
        return  true;
    }
    return false;
}
/**
 * 数据脱敏
 * @param $string 需要脱敏值
 * @param int $start 开始
 * @param int $length 结束
 * @param string $re 脱敏替代符号
 * @return bool|string
 * 例子:
 * dataDesensitization('18811113683', 3, 4); //188****3683
 * dataDesensitization('乐杨俊', 0, -1); //**俊
 */
function dataDesensitization($string, $start = 0, $length = 0, $re = '*')
{
    if (empty($string)){
        return false;
    }
    $strarr = array();
    $mb_strlen = mb_strlen($string);
    while ($mb_strlen) {//循环把字符串变为数组
        $strarr[] = mb_substr($string, 0, 1, 'utf8');
        $string = mb_substr($string, 1, $mb_strlen, 'utf8');
        $mb_strlen = mb_strlen($string);
    }
    $strlen = count($strarr);
    $begin = $start >= 0 ? $start : ($strlen - abs($start));
    $end = $last = $strlen - 1;
    if ($length > 0) {
        $end = $begin + $length - 1;
    } elseif ($length < 0) {
        $end -= abs($length);
    }
    for ($i = $begin; $i <= $end; $i++) {
        $strarr[$i] = $re;
    }
    if ($begin >= $end || $begin >= $last || $end > $last) return $string;
    return implode('', $strarr);
}


function generate_order_number(string $prefix = null,\think\Model $checkModel = null,string $modelField = "order_sn"){
    $snowflake = new \Godruoyi\Snowflake\Snowflake();
    //32位
    if (PHP_INT_SIZE == 4) {
        $result = abs($snowflake->id());
    } else {
        $result = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->id();
    }
    $result = $prefix.$result;
    if ($checkModel){
        $record = $checkModel->where($modelField,$result)->find();
        if ($record){
            generate_order_number($prefix,$checkModel,$modelField);
        }
    }
    return $result;
}
function trimString(string $string, $maxLength = 10) {
    if (mb_strlen($string, 'utf8') <= $maxLength) {
        return $string;
    }
    return mb_substr($string, 0, $maxLength, 'utf8') . '...';
}
